<?php
if (!defined("APP_PATH")) {
    define('APP_PATH',__DIR__.'/../application/');
    // 加载框架引导文件
    require  __DIR__.'/../thinkphp/start.php';
}

use think\Db;
use think\Exception;
use think\Log;

echo "<pre>";
//每20分钟触发一次
if(config("site.uninv_switch")) uninvprize();

function uninvprize()
{
    $debug = config("app_debug");
    if (php_sapi_name() != 'cli' && !$debug) {
        echo '只能在cli模式下或者开启调试模式运行：' . date('Y-m-d H:i:s') . "\r\n";die;
    }

    echo '开始执行的时间：'.date('Y-m-d H:i:s')."\r\n";
    $redis = rds();
    $bkey = 'uninvprize';
    if($debug) delkey($redis,$bkey);//测试
    $op = $redis->set($bkey,1,['NX','EX'=>1080]);
    if(!$op){
        echo '请勿频繁操作：'.date('Y-m-d H:i:s')."\r\n";
        goto END;
    }

//    if($debug){
//        $day = 0;//测试
//    }else{
        $day = 86400;
//    }

    $time = time();
//    $d = date('Ymd');
    $prefix = config('database.prefix');
    //\db()->execute("SET sql_mode=(SELECT REPLACE(@@sql_mode,'ONLY_FULL_GROUP_BY',''))");//本地防止报错
    $where = [
        't.type' => 0,
        't.isout' => 0,
        't.status' => 1,
    ];
    $orders = \db('tron_order')
        ->alias('t')
        ->join('user u','t.uid=u.id')
        ->where($where)
        ->order(['t.uid'=>'asc','t.id'=>'asc'])
        ->group('t.uid')
        ->field('t.id,t.uid,t.type,u.lasttime,u.untxday,u.credit1,t.createtime')
        ->select();
    $where = [
        'type' => 1,
        'status' => 1,
    ];
    $invs = \db('tron_order')
        ->where($where)
        ->order(['uid'=>'asc','id'=>'desc'])
        ->group('uid')
        ->column('id,uid,type,createtime','uid');
//    $lua_sy = '';
    $update_lasttime = '';
    $update_untxday = '';
    $bi = config("site.uninv_bi")/100;
    foreach($orders as $order){
        $order['untxday']++;
        //最后的时间 如果有提现过
        if(empty($invs[$order['uid']])){
            $lasttime = $order['createtime'];
        }else{
            //判断提现是否在投资之后
            if($invs[$order['uid']]['createtime'] > $order['createtime']){
                $lasttime = $invs[$order['uid']]['createtime'];
            }else{
                $lasttime = $order['createtime'];
            }
        }

        if($order['lasttime'] > $lasttime){
            $lasttime = $order['lasttime'];
        }

        $lasttime = $lasttime+$day;
        if($lasttime <= $time){
            $sy = $order['credit1'] * $bi * $order['untxday'];//不体现奖励参数
            echo $order['uid'].'--不提现收益:'.$sy.">>>";
            $lua_sy = <<<LUA
            local user_id = KEYS[1]
            local static_sy_key = KEYS[2]
            local add_sy = ARGV[1]
            local user_sy = ARGV[2]
            redis.call('hIncrByFloat',user_sy,user_id,add_sy)
            redis.call('hIncrByFloat',static_sy_key,user_id,add_sy)
            return true
LUA;
            $res = $redis->eval($lua_sy,['user_'.$order['uid'],REDIS_PREFIX.'static_sy',$sy,REDIS_PREFIX.'user_sy'],2);
            if($res === false){
                echo $order['uid']."---不提现奖励失败\r\n";
                continue;
            }
            $update_lasttime .= " when id={$order['uid']} then '{$lasttime}'";
            $update_untxday .= " when id={$order['uid']} then untxday+1";
        }

    }
    unset($orders,$invs);

    if($update_lasttime && $update_untxday){
//        $lua_sy .= " return true";
        db::startTrans();
        try {
            \db()->execute("UPDATE {$prefix}user SET lasttime=(case {$update_lasttime} else lasttime end),untxday=(case {$update_untxday} else untxday end)");
//            $res = $redis->eval($lua_sy);
//            if($res === false){
//                throw new \Exception("Redis+Lua执行失败---不提现奖励发放异常");
//            }
            db::commit();
        }catch (\Exception $e){
            db::rollback();
            Log::error($e->getMessage());
            echo $e->getMessage();
            echo '执行失败：'.date('Y-m-d H:i:s')."\r\n";
        }
    }else{
        echo '没有需要发放的奖励：'.date('Y-m-d H:i:s')."\r\n";
    }

    delkey($redis,$bkey);
    END:
    echo '结束执行的时间：'.date('Y-m-d H:i:s')."\r\n";
}


